What will be the output of the following code snippet?var x = 10;funct...
Variable hoisting causes the declaration of 'var x' inside the function to be hoisted to the top. However, it is initialized with the value 'undefined' before the assignment. Therefore, the output is 'undefined'.
View all questions of this test
What will be the output of the following code snippet?var x = 10;funct...
Explanation:
The output of the code snippet will be undefined.
Code Analysis:
- The code snippet declares a variable x and assigns it the value 10.
- It then defines a function called foo.
- Inside the foo function, a new variable x is declared using the var keyword.
- The console.log statement inside the function tries to log the value of x.
- Finally, the foo function is called.
Variable Hoisting:
- JavaScript has a concept called hoisting where variable and function declarations are moved to the top of their containing scope during the compilation phase.
- However, only the declarations are hoisted, not the initializations.
- In the code snippet, the variable x inside the foo function is hoisted to the top of the function scope.
- Therefore, the declaration of var x; is moved to the top of the foo function.
- As a result, the original x variable inside the function is shadowed by the hoisted variable declaration.
- Since the hoisted variable declaration does not have an initialization, it is assigned the value undefined by default.
Output Explanation:
- When the foo function is called, it tries to log the value of x.
- However, since the hoisted variable declaration is assigned the value undefined, that is what gets logged to the console.
- The original x variable outside the function remains unaffected and retains its value 10.
Therefore, the output of the code snippet is undefined.